package cn.xinfei.xdecision.data.core.util;

import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataException;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.TimeZone;

public class JsonProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
        OBJECT_MAPPER.setTimeZone(TimeZone.getDefault());
        OBJECT_MAPPER.registerModule(new SimpleModule());
        OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static ObjectMapper getMapper() {
        return OBJECT_MAPPER;
    }

    public static synchronized <M> M fromJsonSafety(String json, Class<M> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            LOGGER.error("error in json serialization", e);
            return null;
        }
    }

    public static <M> M fromJsonOrException(String json, Class<M> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            throw new XDecisionDataException(XDecisionDataExceptionType.COMMON_SERVER_ERROR, "error in json serialization", e);
        }
    }

    public static synchronized String toJsonSafety(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error("error in json deserialization", e);
            return null;
        }
    }

    public static String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error("error in json deserialization", e);
            return null;
        }
    }

    public static String toJsonOrException(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new XDecisionDataException(XDecisionDataExceptionType.COMMON_SERVER_ERROR,
                    "error in json deserialization", e);
        }
    }

    public static <M> M convert(Object object, Class<M> clazz) {
        return OBJECT_MAPPER.convertValue(object, clazz);
    }

}
